package com.leyou.cart.service;


import com.leyou.cart.client.GoodsClient;
import com.leyou.cart.intercept.UserIntercept;
import com.leyou.cart.pojo.Cart;
import com.leyou.common.pojo.UserInfo;
import com.leyou.common.util.JsonUtils;
import com.leyou.item.pojo.Sku;
import net.minidev.json.JSONUtil;
import org.apache.commons.lang.StringUtils;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

@Service
public class CartService {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private GoodsClient goodsClient;

    //redis的hash类型的大key  将他写成一个常量
    static final String KEY_PREFIX = "leyou:cart:uid:";


    public void addCart(Cart cart) {


        //先获取到userInfo对象
        UserInfo userInfo = UserIntercept.getUserInfo();
        
        //在Redis里面获取数据  如果没有就在下面存一遍
        BoundHashOperations<String, Object, Object> hashKey = redisTemplate.boundHashOps(KEY_PREFIX + userInfo.getId());

        //判断有没有这个sku
        Boolean bool = hashKey.hasKey(cart.getSkuId().toString());
        Integer num = cart.getNum();
        if (bool){
            String skuJson = hashKey.get(cart.getSkuId().toString()).toString();
            //通过反序列化成cart对象
            cart = JsonUtils.parse(skuJson, Cart.class);
            //购物车里面有这个商品了  就对它的数量进行修改
            cart.setNum(cart.getNum()+num);

        }else {
            //获取sku对象
            Sku sku = goodsClient.getSkuById(cart.getSkuId());

            cart.setUserId(userInfo.getId());
            cart.setImage(StringUtils.isBlank(sku.getImages()) ? "" : sku.getImages().split(",")[0]);
            cart.setPrice(sku.getPrice());
            cart.setOwnSpec(sku.getOwnSpec());
            cart.setTitle(sku.getTitle());
        }
        //将修改完的数据  在存入到redis里面
        //将数据保存
        hashKey.put(cart.getSkuId().toString(),JsonUtils.serialize(cart).toString());
    }
}
